/*--------------------------------+
| ArcEngine-CSprite.cpp			  |
|								  |
| BrokenGlass				      |
|								  |
| Last Change:					  |
+--------------------------------*/

// This file defines member functions, etc

#include "stdarg.h"
#include "SDL_Image.h"
#include "CSprite.h"
#include "Log.h"

extern SDL_Surface *screen;

CSprite::CSprite()
{
	m_bltrect.x = 0;
	m_bltrect.y = 0;
	m_bltrect.w = 0;
	m_bltrect.h = 0;
	m_sprite = NULL;
}

CSprite::~CSprite()
{
	if (m_sprite)
	{
		SDL_FreeSurface(m_sprite);
		m_sprite = NULL;
	}
}

// COLOR KEYED
bool CSprite::init(const char *filename, Uint8 r, Uint8 g, Uint8 b)
{
	printf(">> Loading Sprite: %s...\n", filename);
	m_sprite = IMG_Load(filename);

	if (m_sprite == NULL)
	{
		printf("ERROR: Couldn't load %s: %s\n", filename, SDL_GetError());
		log_add("ERROR: Couldn't load a sprite.\n");
		return false;
	}
	if (SDL_SetColorKey(m_sprite, SDL_SRCCOLORKEY | SDL_RLEACCEL, SDL_MapRGB(m_sprite->format, r, g, b)) < 0)
	{
		printf("ERROR: Couldn't set colorkey + RLE for %s: %s\n", filename, SDL_GetError());
		log_add("ERROR: Couldn't set a colorkey + RLE.\n");
		return false;
	}
	SDL_Surface *temp;
	if ((temp = SDL_DisplayFormat(m_sprite)) == NULL)
	{
		printf("ERROR: Couldn't convert %s to display format: %s\n", filename, SDL_GetError());
		log_add("ERROR: Couldn't convert sprite to display format\n");
		return false;
	}
	SDL_FreeSurface(m_sprite);
	m_sprite = temp;

	m_bltrect.w = m_sprite->w;
	m_bltrect.h = m_sprite->h;
	return true;
}

// NON-COLORED KEY
bool CSprite::init(const char *filename)
{
	printf(">> Loading Sprite: %s...\n", filename);
	m_sprite = IMG_Load(filename);

	if (m_sprite == NULL)
	{
		printf("ERROR: Couldn't load %s: %s\n", filename, SDL_GetError());
		log_add("ERROR: Couldn't load a sprite.\n");
		return false;
	}
	SDL_Surface *temp;
	if ((temp = SDL_DisplayFormat(m_sprite)) == NULL)
	{
		printf("ERROR: Couldn't convert %s to display format: %s\n", filename, SDL_GetError());
		log_add("ERROR: Couldn't convert sprite to display format\n");
		return false;
	}
	SDL_FreeSurface(m_sprite);
	m_sprite = temp;

	m_bltrect.w = m_sprite->w;
	m_bltrect.h = m_sprite->h;
	return true;
}

bool CSprite::draw(int x, int y)
{
	m_bltrect.x = x;
	m_bltrect.y = y;

	if(SDL_BlitSurface(m_sprite, NULL, screen, &m_bltrect) < 0)
	{
		fprintf(stderr, "BlitSurface error: %s\n", SDL_GetError());
		log_add("BlitSurface error has occurred.\n");
		return false;
	} 
	return true;
}

